const axios = require('axios');
const moment = require('moment');
const querystring = require('querystring');
const fs = require('fs');
const branchList = require("./branch.json")
const pool = require("../../sqlSrver/msSqlServer");
const poolConnect = pool.connect();
const mssql = require("mssql");






async function insetDataForYiDa(baseData, dingdingToken) {
    const { date, branch_no, branch_name, sale_qnty, sale_money, sale_count, sale_prc, qnty_prc } = baseData;
    const formDataJson = {
        dateField_lnu5sqy7: date,
        textField_lnu5sqy8: branch_no,
        textField_lnu5sqy9: branch_name,
        textField_lnu5sqya: sale_qnty,
        textField_lnu5sqyb: sale_money,
        textField_lnu5sqyc: sale_count,
        textField_lnu5sqyd: sale_prc,
        textField_lnu5sqye: qnty_prc
    }

    if(sale_qnty == "null" || !sale_qnty){
        index += 1;
        if (index > 21) {
            index = 0;
            addDay += 1;
        }
        setTimeout(() => { findDataTable() }, 2000);
        return
    }
    axios({
        method: 'post',
        url: 'https://api.dingtalk.com/v1.0/yida/forms/instances',
        headers: {
            'Content-Type': 'application/json',
            "x-acs-dingtalk-access-token": `${dingdingToken.expireIn}`
        },
        data: {
            "appType": "APP_X0HZ0UOS6RNUJPPXTE7T",
            "systemToken": "WF866A818RZDURZ17BANEDQVYDW52IOXE37MLK65",
            "userId": "212859384738996276",
            "formUuid": "FORM-YU966T91AB6F99377AV8LCIN6Q8F3U1LS5UNL3",
            "formDataJson": JSON.stringify(formDataJson)
        }
    }).then((res) => {
        console.log(res.data);
        console.log("--------------------------------数据插入成功--------------------------------------------------------------")
        console.log("--------------------------------res.data---------------------------------");
        index += 1;
        if (index > 21) {
            index = 0;
            addDay += 1;
        }
        setTimeout(() => { findDataTable() }, 2000);

    }).catch((error) => {
        console.log("------------------------error---------------");
        console.log(error);
        console.log("------------------------error---------------");

    })

}




// async function concotSql(baseData, res) {
//     const { date, branch_no, branch_name, sale_qnty, sale_money, sale_count, sale_prc, qnty_prc } = baseData;
//     const insetSql = `INSERT INTO Store_Sales_Report (date, branch_no, branch_name, Sales_quantity, sales_amount, Number_of_trading_customers, Customer_unit_price, Unit_price_of_parts) VALUES (?,?,?,?,?,?,?,?)`
//     const insetDataList = [date, branch_no, branch_name, sale_qnty, sale_money, sale_count, sale_prc, qnty_prc]
//     try {
//         let appentData = {
//             date,
//             branch_no,
//             branch_name,
//             Sales_quantity: sale_qnty,
//             sales_amount: sale_money,
//             Number_of_trading_customers: sale_count,
//             Customer_unit_price: sale_prc,
//             Unit_price_of_parts: qnty_prc
//         }
//         //  日期(date) 门店编号(branch_no) 门店名称(branch_name) 销售数量(sale_qnty) 销售金额(sale_money) 交易客数(sale_count) 客单价(sale_prc) 件单价(qnty_prc)
//         add(appentData, "Store_Sales_Report", (a, b) => {
//             //  res.send({a,b});
//             console.log({ a, b })
//         })
//         index += 1;
//         if (index > 8) {
//             index = 0;
//             addDay += 1;

//         }
//         setTimeout(() => { findDataTable() }, 2000);
//     } catch (error) {
//         // console.error('Error creating time table:', error);
//         // res.status(500).send('Failed to create time table');
//     }
// }


let index = 0;
let addDay = 0;
const startDate = "2022-03-24";
const upDataLocalhostCookie = (content, req) => {
    fs.writeFile('./src/controller/cookie.txt', content, err => {
        if (err) {
            console.error(err, "fs.writeFile");
        }
        findDataTable(req)
        // file written successfully
    });
}

async function Login(req, res, next) {
    let TimeOut = moment().format("YYYY-MM-DD HH:mm:ss");
    let formData = {
        id: 1001,
        password: "Siss",
        onlineQuery: false,
        isPos: 0,
        csflag: "",
        readPrivacy: true,
        wxOpenId: null,
        cacheMenuStyle: false
    }
    const postData = querystring.stringify(formData);
    axios({
        method: 'post',
        url: 'http://localhost:8032/api/Login/Login',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': `USER_BROWSER_FLAG=; TimeOut=${TimeOut}; TimeOut_old=${TimeOut}`
        },
        data: postData
    }).then(res => {
        let content = res.headers["set-cookie"].join(";");
        upDataLocalhostCookie(content, req);
    }).catch(error => {
        console.log(error);
    });
}


async function findDataTable(req, resFuc, next) {
    const branchData = branchList[index];
    console.log("==================================当前数据==============================================");
    console.log(branchData.name, moment(startDate).add(addDay, 'days').format("YYYY-MM-DD hh:mm:ss"));
    console.log("----------------------------------------------------------------------------------------");
    let cookie = fs.readFileSync("./src/controller/cookie.txt", "utf-8");
    let formData = {
        sort: "branch_no",
        order: "ASC",
        loadAll: false,
        beginDate: `${moment(startDate).add(addDay, 'days').format("YYYY-MM-DD")} 00:00:00`,
        endDate: `${moment(startDate).add(addDay, 'days').format("YYYY-MM-DD")} 23:59:59`,
        groupFields: null,
        sumFields: null,
        branchNo: Number(branchData.id),
        menuId: "R201",
        gridFlag: "RptTsxBranchSaleSummaryGrid",
        "cachedCondition[beginDate]": `${moment(startDate).add(addDay, 'days').format("YYYY-MM-DD")} 00:00:00`,
        "cachedCondition[endDate]": `${moment(startDate).add(addDay, 'days').format("YYYY-MM-DD")} 23:59:59`,
        "cachedCondition[groupFields]": null,
        "cachedCondition[sumFields]": null,
        "cachedCondition[branchNo][value]": Number(branchData.id),
        "cachedCondition[branchNo][text]": branchData.name,
        "cachedCondition[dateControl]": "autoRange",
        "cachedCondition[saveCache]": 0,
        page: 1,
        rows: 200
    }
    const postData = querystring.stringify(formData);
    axios({
        method: 'post',
        url: 'http://localhost:8032/api/YunReport/Query',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': cookie
        },
        data: postData
    }).then(res => {
        if (!res.data.rows) {
            Login();
            return
        }
        const { sale_qnty, sale_money, sale_count, sale_prc, qnty_prc } = res.data.rows[0] || {};
        let content = res.headers["set-cookie"].join(";");
        // upDataLocalhostCookie(content);
        if (!sale_qnty || !sale_money || !sale_count || !sale_prc || !qnty_prc) {
            index += 1;
            if (index > 8) {
                index = 0;
                addDay += 1;
            }
            setTimeout(() => { findDataTable() }, 2000);
        }
        let insetData = {
            date: moment(startDate).add(addDay, 'days').valueOf(),
            branch_no: Number(branchData.id),
            branch_name: branchData.name,
            sale_qnty,
            sale_money,
            sale_count,
            sale_prc,
            qnty_prc
        }
        insetDataForYiDa(insetData, req);
        // concotSql(insetData, resFuc);

    }).catch(error => {
        console.log(error);
    });
}


// 获取钉钉token




module.exports = {
    Login,
    findDataTable,
    insetDataForYiDa
}



